package org.club.common.util;

import org.club.common.model.entity.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCacheHelper {
    @Autowired
    private StringRedisTemplate redisTemplate;  // 非静态变量
    // 将验证码文本存储到 Redis 中，并设置过期时间
    public String setVerifyCode(String codeText,Integer timeout) {
        try{
            // 随机生成一个唯一键（UUID）用于存储验证码文本
            String key = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(key, codeText, timeout, TimeUnit.MINUTES);
            return key;
        }catch (NullPointerException e) {
            throw new RuntimeException("RedisTemplate未正确注入，请检查Redis配置或Bean定义");
        }catch (RedisConnectionFailureException e) {
            throw new RuntimeException("Redis连接失败，请检查服务器状态或网络配置");
        }catch (IllegalArgumentException e) {
            System.out.println(timeout);
            throw new RuntimeException("过期时间参数不合法，需为非负数");
        }catch (RedisSystemException e) {
            throw new RuntimeException("Redis操作失败：" + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("未知错误：" + e.getMessage());
        }
    }
      /**
         * 验证验证码
         *
         * @param verifyCodeKey 验证码的唯一键
         * @param verifyCode    用户输入的验证码
         * @throws BusinessException 验证码错误或过期
         */
        public void validateVerifyCode(String verifyCodeKey, String verifyCode) throws BusinessException {
            System.out.println("CodeKey:" + verifyCodeKey);
            String storedVerifyCode = redisTemplate.opsForValue().get(verifyCodeKey);
            System.out.println("Code: " + storedVerifyCode);
            if (storedVerifyCode == null || !storedVerifyCode.equalsIgnoreCase(verifyCode)) {
                throw new BusinessException(400, "验证码失效或错误");
            }
            redisTemplate.delete(verifyCodeKey);
        }
}
